package socket;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by :Infaraway
 * DATE : 2017/3/4
 * Time : 0:31
 * Funtion : 测试使用socket通信在服务端和客户端传递文件
 */
public class SocketForFile {

    @Test
    public void SocketServerSocket() throws IOException {

        //创建ServerSocket对象
        ServerSocket serverSocket = new ServerSocket(22222);
        //接受客户端的请求，并且得到socket对象
        Socket socket = serverSocket.accept();

        //输出 服务器和客户端进行交互

        //本地读取文件
        InputStream in = new FileInputStream("SocketForFile.jpg");
        byte [] buffer = new byte[1024];
        int len = 0;

        //将文件输出到客户端
        OutputStream out = socket.getOutputStream();
        while ((len = in.read(buffer)) != -1){
            out.write(buffer, 0, len);
        }

        //关闭流
        out.close();
        in.close();
        //关闭socket
        socket.close();
        serverSocket.close();
        System.out.println("Server is start...");
    }

    @Test
    public void SocketClientSocket() throws IOException {

        InetAddress address = InetAddress.getByName("127.0.0.1");
        //客户端创建Socket对象，并且同时向服务器端发出请求
        Socket socket = new Socket(address, 22222);

        //使用输入输出流进行数据交互

        //获取文件到本地
        InputStream in = socket.getInputStream();
        OutputStream out = new FileOutputStream("d:\\socketClient.jpg");

        byte [] buffer = new byte[1024];
        int len = 0;

        while ((len = in.read(buffer)) != -1){
            out.write(buffer, 0, len);
        }

        out.close();
        in.close();
        socket.close();
    }

}
